<template>
  <div class="container">
    <span class="text">请点击下面加号选择上传修改头像</span>
    <!--1.action需要修改-->
    <el-upload
      action=""
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :http-request="myUpload"
      :auto-upload="false"
      ref="upload"
      :limit="1"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-button type="primary" style="margin-top: 10px" @click="submitUpload(1)"
      >上传</el-button
    >
  </div>
</template>
<script>
import request from '@/api/request'

export default {
  data() {
    return {
      /*上传图片*/
      dialogImageUrl: '',
    }
  },
  methods: {
    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
    },

    submitUpload(value) {
      if ((value = 1)) {
        //上传图片
        //找到ref为upload的上传组件，调用该组件的submit方法,会自动调用:http-request指定的方法
        this.$refs['upload'].submit()
      }
    },

    //上次文件到服务器
    myUpload(content) {
      //content.file就是要上传的文件
      //FormData可以用于处理文件对象
      var param = new FormData()
      param.append('file', content.file)
      request({
        url: '/upload',
        method: 'post',
        data: param,
      }).then((res) => {
        if (res.code === 200) {
          this.dialogImageUrl = res.data
          this.updateAvatar()
        }
      })
    },

    //上传到数据库
    updateAvatar() {
      var param = new URLSearchParams()
      param.append('avatarUrl', this.dialogImageUrl)
      request
        .patch('/student/updateAvatar', param)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message)
          }
        })
        .catch((error) => {
          this.$message.error(error)
        })
    },

    //限制文件选择数量
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
      )
    },
  },
}
</script>
<style scoped>
/*上传页面样式*/
.container {
  width: 80%;
  margin-left: 5%;
  margin-top: 5%;
}
.text {
  display: flex;
  margin-top: 2%;
  margin-bottom: 30px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 20px;
  color: gray;
}
/*上传头像样式*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-left: 60px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
